# -*- coding: utf-8 -*-

# @File  : logs.py
# @Author: Lomo
# @Site  : lomo.space
# @Date  : 2020-02-13
# @Desc  : Logs


import os
import time
import datetime
from functools import wraps

from config.config import PROJECT_DIR, LOG_DIR


class MRYT_LOG(object):
    def __init__(self, log_file_name=''):
        self.file_path = PROJECT_DIR + LOG_DIR
        if not log_file_name or not os.path.exists(self.file_path + '/' + log_file_name):
            self.log_file_name = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.log'
            os.system('touch {0}/{1}'.format(self.file_path, self.log_file_name))
        else:
            self.log_file_name = log_file_name

        self.log_file = self.file_path + '/' + self.log_file_name
        if not os.path.exists(self.log_file):
            raise Exception('日志目录下不存在名为: {0} 的文件'.format(log_file_name))

    def __call__(self, func):
        @wraps(func)
        def wrapper_function(*args, **kwargs):
            log_str = MRYT_LOG.format_log_str(func.__name__ + 'was called.')
            # print(log_str)
            # TODO Improve: 记录更多接口测试过程中值
            res = func(*args, **kwargs)
            res_str = MRYT_LOG.format_log_str(func.__name__ + ' 方法执行后返回结果为: ' + str(res))
            with open(self.log_file, mode='a', encoding='utf-8') as opened_file:
                opened_file.write(log_str + '\n')
                opened_file.write(res_str + '\n')

            return res
        return wrapper_function

    @staticmethod
    def format_log_str(log_str):
        c_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return c_time + ' ' + log_str


def MRYT_TIMER(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        end_time = time.time()
        print("花费时间：{0}秒".format(end_time - start_time))
        return res
    return wrapper
